﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using TaskRecord.Web.Common;
using TaskRecord.Web.EntityFramework;

namespace TaskRecord.Web.Dal
{
    public class TaskRecordDal:IDal
    {
        public List<EntityFramework.TaskRecord> GetTaskRecords(DateTime queryDate)
        {

            var queryTomorrow = queryDate.Date.AddDays(1);
            var queryYestoday = queryDate.Date;
            using (var db = new TaskRecordDbContext())
            {
                var records = db.Tasks
                    .Include(t=>t.Team)
                    .Include(t=>t.Source)
                    .Include(t=>t.Status)
                    .Where(x =>(x.Date>=queryYestoday&&x.Date<=queryTomorrow)).ToList();
                return records;
            }
        }

        public void EditTaskRecord(EntityFramework.TaskRecord taskRecord)
        {
            using (var db = new TaskRecordDbContext())
            {
                var record = db.Tasks.Single(x => x.Id == taskRecord.Id);
                var source = db.TaskRecordSources.Single(x => x.Id == taskRecord.Source.Id);
                var team = db.TaskRecordTeams.Single(x => x.Id == taskRecord.Team.Id);
                var status = db.TaskRecordStatus.Single(x => x.Id == taskRecord.Status.Id);

                record.Content = taskRecord.Content;
                record.Car = taskRecord.Car;
                record.Source = source;
                record.Status = status;
                record.Team = team;
                db.Entry(record).State = EntityState.Modified;
                db.SaveChanges();
            }
        }

        public void AddTaskRecord(EntityFramework.TaskRecord taskRecord)
        {
            taskRecord.Date=DateTime.Now;
            using (var db = new TaskRecordDbContext())
            {
                var source = db.TaskRecordSources.Single(x => x.Id == taskRecord.Source.Id);
                var team = db.TaskRecordTeams.Single(x => x.Id == taskRecord.Team.Id);
                var status = db.TaskRecordStatus.Single(x => x.Id == taskRecord.Status.Id);
                taskRecord.Source = source;
                taskRecord.Status = status;
                taskRecord.Team = team;
                db.Tasks.Add(taskRecord);
                db.SaveChanges();
            }
        }

    }
}